<template>
  <div class="manage">
    <el-dialog
      :title="`${status}`+'用户'"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="30%"
      style="text-align: center"
      :before-close="handleClose"
    >
      <!--用户的表单信息-->
      <el-form ref="form" :rules="rules" :inline="true" :model="form" label-width="80px" label-position="right">
        <el-form-item label="姓名" prop="name">
          <el-input placeholder="请输入姓名" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="code">
          <el-input placeholder="请输入工号" v-model="form.code"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordDeed">
          <el-input type="password" placeholder="请确认密码" v-model="form.passwordDeed"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select  v-model="form.roleId" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="岗位" prop="postId">
          <el-select  v-model="form.postId" placeholder="请选择岗位">
            <el-option v-for="item in postList" :key="item.postId" :label="item.postName" :value="item.postId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="部门" prop="deptId">
          <el-select  v-model="form.deptId" placeholder="请选择部门">
            <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <div class="manage-header">
      <el-button @click="handleAdd" type="primary" size="mini">
        + 新增
      </el-button>
      <!--          form搜索区域-->
<!--      <el-form :inline="true" :model="userForm" size="mini">-->
<!--        <el-form-item label="状态：" prop="is_active">-->
<!--          <el-select v-model="userForm.is_active" placeholder="请选择状态">-->
<!--            <el-option label="全部" value=""></el-option>-->
<!--            <el-option label="启用" value="1"></el-option>-->
<!--            <el-option label="禁用" value="0"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="姓名：" prop="name" >-->
<!--          <el-input placeholder="请输入姓名" v-model="userForm.name"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="工号：" prop="username">-->
<!--          <el-input placeholder="或输入工号" v-model="userForm.username"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="success" @click="onSubmit" size="mini">查询</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
    </div>
    <div class="common-table">
      <el-table
        stripe
        height="90%"
        border
        size="mini"
        :data="tableData.slice((paginations.current-1)*paginations.pageSize,paginations.current*paginations.pageSize)"
        style="width: 100%">
        <el-table-column
            prop="userId"
            fixed
            label="编号"
            align="center"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          align="center"
        >
          <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.name }}</el-tag>
          </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="code"
          label="工号"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色"
          align="center"
        >
        </el-table-column>
        <el-table-column
            prop="postName"
            label="岗位"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="deptName"
            label="部门"
            align="center"
        >
        </el-table-column>
<!--        <el-table-column-->
<!--            prop="is_active"-->
<!--            label="工号状态"-->
<!--            align="center"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <span :style="{ color: scope.row.is_active ===true ? 'green' :'red'}"-->
<!--            >-->
<!--              {{scope.row.is_active===true?'启用':'禁用'}}-->
<!--            </span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="200px"
        >
          <template slot-scope="scope">
            <el-button type="primary"
                       size="mini"
                       icon="el-icon-edit"
                       style="background-color: blue"
                       @click="edit(scope.row)"
            >
              编辑
            </el-button>
            <el-button type="info"
                       size="mini"
                       icon="el-icon-s-tools"
                       :style="{background: 'red'}"
                       @click="handleStop(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="paginations.current"
            :page-sizes="[5 ,10, 20, 50, 100]"
            :page-size="paginations.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paginations.total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {userList,userAdd,userDelete,userEdit,userSelect} from '@/api/user'
import {roleList} from "@/api/role";
import {postList} from "@/api/post";
import {deptList} from "@/api/dept";
export default {
  name: 'StaffManagement',
  data () {
    return {
      type:'', //区分el-dialog是新增弹框还是编辑弹框
      status:'新增',
      dialogVisible: false,
      form: {
        name: '',
        code: '',
        password:'',
        passwordDeed: '',
        roleId: '',
        postId:'',
        deptId:''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger:'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入工号',
            trigger:'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger:'blur'
          },
          {
            min:8,
            max:16,
            message: '长度在8到16个字符之间',
            trigger: 'blur'
          },
          {
            pattern:"^(?!.*[！·（）{}【】“”：；，》￥、。‘’——\\s-……%\\n])(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/])[^\\u4e00-\\u9fa5]{8,16}$",
            message: '必须包含数字、小写字母、大写字母',
            trigger: 'blur'
          }
        ],
        passwordDeed: [
          {
            required: true,
            message: '请确认密码',
            trigger:'blur'
          },
          {
            min:8,
            max:16,
            message: '长度在8到16个字符之间',
            trigger: 'blur'
          },
          {
            pattern:"^(?!.*[！·（）{}【】“”：；，》￥、。‘’——\\s-……%\\n])(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/])[^\\u4e00-\\u9fa5]{8,16}$",
            message: '必须包含数字、小写字母、大写字母',
            trigger: 'blur'
          }
        ],
        roleId: [
          {
            required: true,
            message: '请选择角色',
            trigger:'blur'
          }
        ],
        postId:[
          {
            required: true,
            message: '请选择岗位',
            trigger:'blur'
          }
        ],
        deptId:[
          {
            required: true,
            message: '请选择部门',
            trigger:'blur'
          }
        ]
      },
      tableData: [],
      paginations: {
        current: 1, //当前页
        pageSize: 10, //一页显示多少条
        total: 0 //数据总数
      },
      roleList:[],
      postList:[],
      deptList:[]
    }
  },
  mounted() {
    this.created();
  },
  methods: {
    created() {
      roleList().then(res=>{
        if(res.code===200){
          this.roleList = res.data
        }
      })
      postList().then(res=>{
        if(res.code===200){
          this.postList = res.data
        }
      })
      deptList().then(res=>{
        if(res.code === 200){
          this.deptList = res.data
        }
      })
      this.getList(this.paginations.current,this.paginations.pageSize)
    },
    //提交用户表单
    submit () {
      if(this.type==='新增'){
        this.$refs.form.validate((valid) => {
          if (valid) {
            //后续对表单数据的处理
            if (this.form.password === this.form.passwordDeed) {
              let temp={
                code:this.form.code,
                name:this.form.name,
                password:this.form.password,
                roleId:this.form.roleId,
                postId:this.form.postId,
                deptId:this.form.deptId
              }
              userAdd(temp).then((res)=>{
                //新增用户的接口
                if(res.code===200){
                  console.log('新增成功')
                  this.$message.success({
                    message:res.msg,
                    type:'success'
                  })
                }else{
                  console.log(res.msg)
                  this.$message.error(res.msg)
                }
                this.dialogVisible = false
                console.log(this.form, 'form')
                //清空表单数据
                this.$refs.form.resetFields()
                //关闭弹窗
                //重新获取列表的接口
                this.getList(this.paginations.current,this.paginations.pageSize)
              })
            }else{
              this.$message.error('两次密码不一致，请确认')
              this.dialogVisible = true
            }
          }
        })
      }else{
        console.log(this.form)
        console.log(this.form.passwordDeed)
        if (this.form.password === this.form.passwordDeed) {
          let temp={
            code:this.form.code,
            name:this.form.name,
            password:this.form.password,
            roleId:this.form.roleId,
            postId:this.form.postId,
            deptId:this.form.deptId
          }
          console.log(temp)
          userEdit(temp).then((res)=>{
            //新增用户的接口
            if(res.code===200){
              console.log('修改成功')
              this.$message.success({
                message:res.msg,
                type:'success'
              })
            }else{
              console.log(res.msg)
              this.$message.error(res.msg)
            }
            this.dialogVisible = false
            console.log(this.form, 'form')
            //清空表单数据
            this.$refs.form.resetFields()
            console.log(this.form)
            //关闭弹窗
            //重新获取列表的接口
            this.getList(this.paginations.current,this.paginations.pageSize)
          })
        }else{
          this.$message.error('两次密码不一致，请确认')
          this.dialogVisible = true
        }
      }

    },
    //弹窗关闭的时候
    handleClose () {
      if(this.status==='新增'){
        this.dialogVisible = false
        this.$refs.form.resetFields()
        this.form.name = ''
        this.form.roleId = ''
        this.form.postId = ''
        this.form.deptId = ''
        this.form.passwordDeed = ''
        this.form.code = ''
        this.form.password = ''
      }else{
        this.dialogVisible = false
      }
    },
    cancel () {
      this.handleClose()
    },
    edit(row){
      this.type = '编辑'
      this.status = '编辑'
      this.form ={
        name:row.name,
        code:row.code,
        roleId:this.roleList.filter(value => value.roleName === row.roleName)[0].roleId,
        postId: this.postList.filter(value => value.postName === row.postName)[0].postId,
        deptId: this.deptList.filter(value => value.deptName === row.deptName)[0].deptId
      }
      this.dialogVisible = true
    },
    handleStop(row){
      let params={
        userId:row.userId
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText:'取消',
        type:"warning"
      }).then(() =>{
        userDelete(params).then((res)=>{
          if(res.code===200){
            this.$message.success({
              message:res.msg,
              type:'success'
            })
            this.getList(this.paginations.current,this.paginations.pageSize)
          }
        })
      }).catch(() => {

      })
    },
    //分页方法
    handleCurrentChange(val) {
      this.paginations.current = val
      this.getList(val,this.paginations.pageSize);
    },
    handleSizeChange(val) {
      this.paginations.pageSize = val
      this.getList(this.paginations.current ,val);
    },
    //获取的列表数据
    getList (current,pageSize) {
      //获取的列表数据
     userList().then(resp => {
        if (resp.code === 200) {
          console.log(resp.data)
          this.tableData = resp.data
          this.paginations.total = resp.data.length
          this.paginations.current = current
          this.paginations.pageSize = pageSize
        }else{
          this.$message.error(resp.msg)
        }
      })
    },
    handleAdd () {
      this.status = '新增'
      this.type = '新增'
      this.dialogVisible = true
      this.form = {}
    },
    //列表的查询
    onSubmit () {
      this.getList(this.paginations.current,this.paginations.pageSize)
    },
  }
}
</script>

<style lang="less" scoped>
.manage{
  height: 100%;
  .manage-header{
    //display: flex;
    //justify-content: space-between;
    //align-items: flex-start;
    border-bottom: 1px dotted lightgrey;
    padding-bottom: 1em;
  }
  .common-table{
    margin-top: 20px;
    position: relative;
    height: 90%;
    .pager{
      position: absolute;
      bottom: 0;
      right: 20px;
    }
  }
}
</style>
